/*
 *   Copyright 2012-present OSBI Ltd
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */

// Packages
import React from 'react';
import axios from 'axios';
import qs from 'qs';
import { Intent, Position } from '@blueprintjs/core';

// Types
import {
  SAVE_SELECTED_CUBE,
  SAVE_QUERY,
  SAVE_OPEN_QUERY,
  SAVE_QUERY_DESIGNER,
  SWITCH_RENDER
} from './types';

// Actions
import { requestStart, requestSuccess, requestFailure } from './blockUiActions';
import { setQueryProperty } from './queryActions';

// UI
import { BlockUi } from '../components/UI';

// Utils
import { Saiku, Settings } from '../utils';

// Constants
const {
  DEFAULT_RENDER_TYPE,
  DEFAULT_CHART_TYPE,
  QUERY_PROPERTY_DATA
} = Settings;

export const saveQueryAuto = file => async (dispatch, getState) => {
  const { workspace } = getState().workspace;
  const path = file;

  workspace.file = file;

  dispatch(requestStart(<BlockUi message="Saving query..." />));

  dispatch(
    await setQueryProperty({
      [QUERY_PROPERTY_DATA]: JSON.stringify(workspace)
    })
  );

  const { query } = getState().query;
  const rawQuery = JSON.stringify(query);
  const data = {
    name: path,
    file,
    content: rawQuery
  };

  axios
    .post(`${Settings.REST_URL}/api/repository/resource`, qs.stringify(data), {
      headers: {
        'content-type': 'application/x-www-form-urlencoded'
      }
    })
    .then(res => {
      dispatch(saveQuery({ file }));

      Saiku.toasts(Position.TOP_RIGHT).show({
        icon: 'tick',
        intent: Intent.SUCCESS,
        message: 'Saved!'
      });

      dispatch(requestSuccess());
    })
    .catch(error => {
      dispatch(requestFailure());
      Saiku.axiosHandleErrors(
        'actions → workspaceActions.js → saveQueryAuto()',
        error
      );
    });
};

export const saveSelectedCube = selectedCube => {
  return {
    type: SAVE_SELECTED_CUBE,
    payload: selectedCube
  };
};

export const saveQuery = data => {
  return {
    type: SAVE_QUERY,
    payload: data
  };
};

export const saveOpenQuery = data => {
  return {
    type: SAVE_OPEN_QUERY,
    payload: data
  };
};

export const saveQueryDesigner = data => {
  return {
    type: SAVE_QUERY_DESIGNER,
    payload: data
  };
};

export const switchRender = (
  renderMode = DEFAULT_RENDER_TYPE,
  chartType = DEFAULT_CHART_TYPE
) => {
  return {
    type: SWITCH_RENDER,
    payload: { renderMode, chartType }
  };
};
